package video_worker

import (
	"context"
	"log"
	"sync"

	"image_demo/internal/video"
	"image_demo/internal/video_downloader"
)

// Pool 表示视频worker池
type Pool struct {
	videoClient *video.Client
	downloader  *video_downloader.Downloader
	taskChan    chan Task
	wg          sync.WaitGroup
	workerCount int
}

// NewPool 创建新的视频worker池
func NewPool(workerCount int) *Pool {
	return &Pool{
		videoClient: video.NewClient(),
		downloader:  video_downloader.NewDownloader(),
		taskChan:    make(chan Task, workerCount*2),
		workerCount: workerCount,
	}
}

// Start 启动视频worker池
func (p *Pool) Start(ctx context.Context) {
	log.Printf("启动 %d 个视频worker...", p.workerCount)
	for i := 0; i < p.workerCount; i++ {
		p.wg.Add(1)
		go p.worker(ctx, i+1)
	}
}

// Submit 提交任务到视频worker池
func (p *Pool) Submit(ctx context.Context, task Task) bool {
	select {
	case p.taskChan <- task:
		log.Printf("视频任务已提交: %s", task.APIURL)
		return true
	case <-ctx.Done():
		log.Println("程序正在关闭，停止提交新视频任务")
		return false
	default:
		// worker pool已满，等待一下再重试
		log.Printf("视频worker pool已满，等待处理: %s", task.APIURL)
		select {
		case p.taskChan <- task:
			log.Printf("视频任务已提交: %s", task.APIURL)
			return true
		case <-ctx.Done():
			log.Println("程序正在关闭，停止提交新视频任务")
			return false
		}
	}
}

// Stop 停止视频worker池
func (p *Pool) Stop() {
	close(p.taskChan)
	p.wg.Wait()
}

// worker函数，处理视频API调用和视频下载
func (p *Pool) worker(ctx context.Context, id int) {
	defer p.wg.Done()

	for {
		select {
		case task, ok := <-p.taskChan:
			if !ok {
				return
			}

			// 处理视频API调用
			log.Printf("[Video Worker %d] 开始处理视频API: %s", id, task.APIURL)
			videoURL, err := p.videoClient.Call(ctx, task.APIURL)
			if err != nil {
				log.Printf("[Video Worker %d] 视频API调用失败: %s, 错误: %v", id, task.APIURL, err)
				continue
			}

			log.Printf("[Video Worker %d] 获取到视频URL: %s", id, videoURL)

			// 处理视频下载
			if err := p.downloader.DownloadVideo(ctx, videoURL, task.OutputDir); err != nil {
				log.Printf("[Video Worker %d] 视频处理失败: %s, 错误: %v", id, videoURL, err)
				continue
			}

			log.Printf("[Video Worker %d] 视频任务完成: %s", id, task.APIURL)

		case <-ctx.Done():
			log.Printf("[Video Worker %d] 接收到取消信号，退出", id)
			return
		}
	}
}
